/**
 * Copyright (C) 2011 Moss Computing <support@mosscomputing.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.oslef.csv.table;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;

import org.oslef.csv.CSVReader;

/**
 * Permits concise and trivial iteration through the rows of a CSV file.
 */
public final class TableIterator implements Iterator<Row> {

	private final CSVReader r;
	private final HeaderInfo headers;
	
	private String[] next;
	
	public TableIterator(File file) throws FileNotFoundException {
		this(new FileReader(file));
	}

	public TableIterator(Reader reader) {
		r = new CSVReader(reader);
		try {
			headers = new HeaderInfo(parseRecord());
		}
		catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	private String[] parseRecord() throws IOException {
		r.next();
		return r.getColumns();
	}

	public boolean hasNext() {
		if (next == null) {
			try {
				return r.hasNext();
			}
			catch (Exception ex) {
				throw new RuntimeException(ex);
			}
		}
		return next != null;
	}

	public Row next() {
		if (next != null) {
			Row row = new Row(headers, next);
			next = null;
			return row;
		}
		else {
			String[] data;
			try {
				data = parseRecord();
			}
			catch (Exception ex) {
				throw new RuntimeException(ex);
			}
			if (data == null) throw new RuntimeException("No more rows");
			return new Row(headers, data);
		}
	}

	public void remove() {
		throw new RuntimeException("Not supported");
	}
	
	public void close() throws IOException {
		r.close();
	}
}
